<?php

namespace api\modules\v1\models\group;

use api\modules\v1\models\user\User;
use common\models\CacheKeys;
use common\models\friend\FriendApply;
use common\models\Functions;
use common\models\im\Im;
use common\models\im\ImQrcode;
use common\models\Status;
use common\models\user\UserUnusualLog;
use Yii;
use yii\base\Exception;
use yii\helpers\ArrayHelper;

class GroupApply extends \common\models\group\GroupApply
{

    /**
     * 申请群
     * @return array
     */
    public function apply()
    {
        $trans = static::getDb()->beginTransaction();

        try {
            $user = (new User())->checkUser();
            CacheKeys::checkFrequency("APPLY_GROUP_" . $user['id'], 1);

            $groupTxCode = (string) Yii::$app->request->post('group_tx_code', "");
            $message = Yii::$app->request->post('message', '');
            $type = Yii::$app->request->post('type', 0);

            if (!$groupTxCode) {
                throw new Exception('未知群信息！');
            }

            if (!in_array($type, array_keys(Status::GROUP_USER_JOIN_TYPE_MAP))) {
                throw new Exception('未知进群方式！');
            }

            $where['tx_code'] = $groupTxCode;
            $searchGroup = Group::getObjectOneByWhere($where)->with([])->asArray()->one();
            if (empty($searchGroup)) {
                throw new Exception('未知群信息！');
            }

            if ($searchGroup['status'] == Status::COMMON_RADIO_NO) {
                throw new Exception('群已被封禁，无法申请！');
            }

            UserUnusualLog::checkUserUnusual($user['id'],Status::USER_UNUSUAL_TYPE_GROUP_CHAT);

            // 是否加入群聊
            $isGroupUser = GroupUser::getCountByWhere([
                'user_id' => $user['id'],
                'group_id' => $searchGroup['id'],
            ]);
            if ($isGroupUser > 0) {
                throw new Exception('已加入该群，无需重复申请！');
            }
            $applyData['user_id'] = $user['id'];
            $applyData['group_id'] = $searchGroup['id'];
            $check = static::getOneByWhere($applyData, 'id');

            // 群聊邀请开关
            if ($searchGroup['is_auto_enter'] == Status::COMMON_RADIO_NO || ($searchGroup['is_auto_enter'] == Status::COMMON_RADIO_YES && $type = Status::GROUP_USER_JOIN_TYPE_APPLY)) {
                // 生成申请记录 需要群主同意
                $applyData['message'] = $message;
                $applyData['create_time'] = date('Y-m-d H:i:s');
                $applyData['status'] = Status::COMMON_CHECKING_WAITING;
                if ($check) {
                    $res = static::updateData($applyData, ['id' => $check['id']]);
                } else {
                    $applyData['user_id'] = $user['id'];
                    $applyData['user_phone'] = $user['login_name'];
                    $applyData['user_code'] = $user['user_code'];
                    $applyData['user_nick_name'] = $user['nick_name'];
                    $applyData['user_face'] = $user['user_face'];
                    $applyData['user_tx_code'] = $user['tx_code'];
                    //                $applyData['enter_type'] = Status::GROUP_USER_JOIN_TYPE_APPLY; //1-申请进群  2-邀请进群 3-二维码
                    $applyData['enter_type'] = $type; //1-申请进群  2-邀请进群 3-二维码
                    $applyData['status'] = Status::COMMON_CHECKING_WAITING;
                    $applyData['group_id'] = $searchGroup['id'];
                    $applyData['group_tx_code'] = $searchGroup['tx_code'];
                    $applyData['group_code'] = $searchGroup['code'];
                    $applyData['group_image'] = $searchGroup['image'];
                    $applyData['group_name'] = $searchGroup['name'];
                    $applyData['be_invited_status'] = Status::COMMON_CHECKING_SUCCESS;
                    $res = static::insertData($applyData);
                }

                if ($res === false) {
                    throw new Exception('申请失败！');
                }

                FriendApply::notReadApplyNum($user['id'],  $searchGroup['id']);
            }

            // 群聊邀请开关
            if ($searchGroup['is_auto_enter'] == Status::COMMON_RADIO_YES && $type = Status::GROUP_USER_JOIN_TYPE_ER_CODE) {
                // 直接进群
                $groupUser = [];
                $groupUser['group_id'] = $searchGroup['id'];
                $groupUser['group_tx_code'] = $searchGroup['tx_code'];
                $groupUser['group_code'] = $searchGroup['code'];
                $groupUser['group_name'] = $searchGroup['name'];
                //                    $groupUser['group_image'] = $groupInfo['image'];
                $groupUser['user_id'] = $user['id'];
                $groupUser['user_tx_code'] = $user['tx_code'];
                $groupUser['user_face'] = $user['user_face'];
                $groupUser['user_nick_name'] = $user['nick_name'];
                //                    $groupUser['business_card'] = $friendUser['nick_name'];
                $groupUser['business_card'] = '';
                $groupUser['user_code'] = $user['user_code'];
                $groupUser['user_phone'] = $user['login_name'];
                $groupUser['user_type'] = Status::GROUP_USER_TYPE_NORMAL;
                $groupUser['is_shut_up'] = Status::COMMON_RADIO_NO;   //禁言
                $groupUser['is_not_disturbing'] = Status::COMMON_RADIO_NO;   //是否消息免打扰
                $groupUser['is_receive_red_packet'] = Status::COMMON_RADIO_YES;  // 是否可以抢红包
                $groupUser['create_time'] = date('Y-m-d H:i:s');
                $applyData['enter_type'] = $type; //1-申请进群  2-邀请进群 3-二维码
                $groupUser['invite_user_id'] = "";
                $groupUser['invite_user_phone'] = "";
                $groupUser['invite_user_tx_code'] = "";
                $groupUser['invite_user_code'] = "";
                $groupUserRes = static::insertData($groupUser);
                if ($groupUserRes === false) {
                    throw new Exception('进群失败！');
                }

                if ($check) {
                    // 进群以后删除邀请记录
                    GroupApply::deleteAll(['id' => $check['id']]);
                }
                $memberList = [];
                $singleMember['enter_type'] = (string) $type;
                $singleMember['invite_code'] = "0";
                $singleMember['Member_Account'] = (string) $user['tx_code'];
                $singleMember['NameCard'] = $user['nick_name'];
                array_push($memberList, $singleMember);
                // 添加群成员
                $imModel = new Im();
                $addImGroupRes = $imModel->addImGroupUser($searchGroup['tx_code'], $memberList);
                if (!$addImGroupRes) {
                    throw new Exception('操作失败！');
                }

                // 更换群头像 - 群没有上传头像的时候才会更新群头像
                (new Group())->_updateGroupPic($searchGroup['id']);

                // 发送im消息 自己申请
                $publicGroupMessage['message_type'] = Status::MESSAGE_TYPE_GROUP_PUBLIC;
                $publicGroupMessage['type'] = Status::MESSAGE_TYPE_GROUP_USER_APPLY;
                $publicGroupMessage['oneTxCode'] = $user['tx_code'];
                $publicGroupMessage['oneNIckName'] = $user['nick_name'];
                $publicGroupMessage['content'] = $user['nick_name'] . "加入群聊！";

                $imModel->sendGroupMessage($searchGroup['tx_code'], $publicGroupMessage);

                // 未读数量
                FriendApply::notReadApplyNum($user['id'], $searchGroup['id']);
            }



            $trans->commit();
            return Functions::formatRestAPI(0, '申请信息已发送，请等待审核!');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 申请列表
     * @return array
     */
    public function getList()
    {
        try {
            $page = (int) Yii::$app->request->get('page', 1);
            $size = (int) Yii::$app->request->get('size', 20);

            $user = (new User())->checkUser();

            $where = $andWhere = [];
            $groupIds = GroupUser::getFormArray(['user_id' => $user['id'], 'user_type' => [Status::GROUP_USER_TYPE_HOME, Status::GROUP_USER_TYPE_MANAGE]], 'group_id', 'group_id');
            //            $where['group_id'] = $groupIds;
            $andWhere[] = [
                'or',
                [
                    'and',
                    ['be_invited_status' => Status::COMMON_CHECKING_SUCCESS],
                    ['status' => Status::COMMON_CHECKING_WAITING],
                    ['group_id' => $groupIds],
                ],
                [
                    'and',
                    ['be_invited_status' => Status::COMMON_CHECKING_WAITING],
                    ['user_id' => $user['id']],
                ],
            ];


            $count = static::getCountByAndWhere($where, $andWhere);
            $data = static::setPageinationAPI($page, $size, $count);

            $offset = ($page - 1) * $size;
            $list = static::getObjectByAndWhere($where, $andWhere, ['*'], 'id DESC', $offset, $size)->with([
                'applyUser' => function ($q) {
                    $q->select(['id', 'login_name', 'user_face', 'nick_name']);
                },

                'inviteUser' => function ($q) {
                    $q->select(['id', 'login_name', 'user_face', 'nick_name']);
                },
            ])->asArray()->all();
            $result = [];
            foreach ($list as $v) {
                $tmp = [];
                $applyUser = ArrayHelper::getValue($v, 'applyUser', []);
                $inviteUser = ArrayHelper::getValue($v, 'inviteUser', []);

                $tmp['id'] = (int) $v['id'];
                $tmp['user_id'] = (int) $v['user_id'];
                $tmp['user_code'] = $v['user_code'];
                $tmp['message'] = $v['message'];
                $tmp['status'] = $v['status'];
                $tmp['group_id'] = $v['group_id'];
                $tmp['group_code'] = $v['group_code'];
                $tmp['create_time'] = $v['create_time'];
                $tmp['user_face'] = $applyUser ? static::getAvatar($applyUser['user_face']) : '';
                $tmp['nick_name'] = $applyUser ? $applyUser['nick_name'] : '';
                $tmp['group_name'] = $v['group_name'];
                $tmp['group_image'] = static::getImages($v['group_image']);
                $tmp['be_invited_status'] = $v['be_invited_status'];


                $type = Status::GROUP_APPLY_CHECK_TYPE_MANAGE; // 1-群主和管理员进行审核   2-自己是否同意进群
                $message = $userFace = $nickName = '';

                if ($v['enter_type'] == Status::GROUP_USER_JOIN_TYPE_INVITE) {
                    // 被邀请
                    if ($v['user_id'] == $user['id']) {
                        $type = Status::GROUP_APPLY_CHECK_TYPE_USER;
                        $message = $inviteUser['nick_name'] . '邀请你加入' . $v['group_name'];
                        $userFace = $inviteUser ? static::getAvatar($inviteUser['user_face']) : '';
                        $nickName = $inviteUser ? $inviteUser['nick_name'] : '';
                    } else {
                        $message = $inviteUser['nick_name'] . '邀请' . $applyUser['nick_name'] . '加入' . $v['group_name'];
                        $userFace = $applyUser ? static::getAvatar($applyUser['user_face']) : '';
                        $nickName = $applyUser ? $applyUser['nick_name'] : '';
                    }
                } else {
                    // 申请
                    $message = $applyUser['nick_name'] . '申请加入' . $v['group_name'] . "。备注：" . $v['message'];
                    $userFace = $applyUser ? static::getAvatar($applyUser['user_face']) : '';
                    $nickName = $applyUser ? $applyUser['nick_name'] : '';
                }

                $tmp['type'] = $type;
                $tmp['message'] = $message;
                $tmp['user_face'] = $userFace;
                $tmp['nick_name'] = $nickName;

                $result[] = $tmp;
            }
            $data['data'] = $result;

            //            FriendApply::notReadApplyNum($user['id']);
            return Functions::formatRestAPI(0, '', $data);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 被邀请群处理 - 用户被邀请 - 是否需要同意入群
     * @return array
     */
    public function beInviteUserCheck()
    {
        $trans = static::getDb()->beginTransaction();

        try {
            $redis = Yii::$app->redis;
            $user = (new User())->checkUser();

            CacheKeys::checkFrequency($user['id'], 1);

            $id = Yii::$app->request->post('id', 0);
            $state = Yii::$app->request->post('state', 0);

            if (!$id) {
                throw new Exception('未知申请信息！');
            }

            if (!$state) {
                throw new Exception('审核状态有误！');
            }

            if (!in_array($state, [Status::COMMON_CHECKING_SUCCESS, Status::COMMON_CHECKING_DEFEAT])) {
                throw new Exception('审核状态有误！');
            }

            $info = static::getOneByWhere(['id' => $id]);
            if (empty($info)) {
                throw new Exception('申请信息不存在！');
            }

            if ($info['be_invited_status'] != Status::COMMON_CHECKING_WAITING) {
                throw new Exception('申请信息已处理！');
            }

            if ($info['user_id'] != $user['id']) {
                throw new Exception('非法请求！');
            }
            
            UserUnusualLog::checkUserUnusual($user['id'],Status::USER_UNUSUAL_TYPE_GROUP_CHAT);

            $groupInfo = Group::getObjectOneByWhere(['id' => $info['group_id']])->with([])->asArray()->one();
            if (empty($groupInfo)) {
                throw new Exception('群信息不存在！');
            }

            if ($groupInfo['status'] == Status::COMMON_RADIO_NO) {
                throw new Exception('群已被封禁！');
            }

            //是否是好友
            $isGroupUser = GroupUser::getCountByWhere([
                'user_id' => $user['id'],
                'group_id' => $info['group_id'],
            ]);
            if ($isGroupUser > 0) {
                throw new Exception('已加入该群，请勿重复处理！');
            }

            $updateData['be_invited_status'] = $state;
            $updateData['be_invited_handle_time'] = date('Y-m-d H:i:s');
            $res = static::updateData($updateData, ['id' => $id]);
            if ($res === false) {
                throw new Exception('操作失败！');
            }

            $inviteGroupUser = GroupUser::getObjectByWhere([
                'user_id' => $info['invite_user_id'],
                'group_id' => $info['group_id'],
            ])->with([
                'inviteUser' => function ($q) {
                    $q->select(['id', 'login_name', 'user_face', 'nick_name', 'tx_code', 'user_code']);
                },

            ])->asArray()->one();

            $memberList = [];
            $imModel = new Im();

            if ($state == Status::COMMON_CHECKING_SUCCESS) {
                // 判断是否是群主或者管理邀请 直接进群
                if (!empty($inviteGroupUser) && in_array($inviteGroupUser['user_type'], [Status::GROUP_USER_TYPE_HOME, Status::GROUP_USER_TYPE_MANAGE])) {
                    $groupImInfo = $imModel->getGroupInfo($groupInfo['tx_code']);
                    if ($groupImInfo['MemberNum'] + 1 >  $groupImInfo['MaxMemberNum']) {
                        throw new Exception('该群人员已达上限！');
                    }

                    // 邀请状态同意  自己处理自己
                    $updateData['handle_user_id'] = $user['id'];
                    $updateData['handle_user_tx_code'] = $user['tx_code'];
                    $updateData['handle_user_code'] = $user['user_code'];
                    $updateData['status'] = $state;
                    $updateData['handle_time'] = date('Y-m-d H:i:s');
                    $res = static::updateData($updateData, ['id' => $id]);
                    if ($res === false) {
                        throw new Exception('操作失败！');
                    }

                    $inviteUser = ArrayHelper::getValue($inviteGroupUser, 'inviteUser', []);
                    $groupUser = [];
                    $groupUser['group_id'] = $groupInfo['id'];
                    $groupUser['group_tx_code'] = $groupInfo['tx_code'];
                    $groupUser['group_code'] = $groupInfo['code'];
                    $groupUser['group_name'] = $groupInfo['name'];
                    //                    $groupUser['group_image'] = $groupInfo['image'];
                    $groupUser['user_id'] = $user['id'];
                    $groupUser['user_tx_code'] = $user['tx_code'];
                    $groupUser['user_face'] = $user['user_face'];
                    $groupUser['user_nick_name'] = $user['nick_name'];
                    //                    $groupUser['business_card'] = $user['nick_name'];
                    $groupUser['business_card'] = '';
                    $groupUser['user_code'] = $user['user_code'];
                    $groupUser['user_phone'] = $user['login_name'];
                    $groupUser['user_type'] = Status::GROUP_USER_TYPE_NORMAL;
                    $groupUser['is_shut_up'] = Status::COMMON_RADIO_NO;   //禁言
                    $groupUser['is_not_disturbing'] = Status::COMMON_RADIO_NO;   //是否消息免打扰
                    $groupUser['is_receive_red_packet'] = Status::COMMON_RADIO_YES;  // 是否可以抢红包
                    $groupUser['create_time'] = date('Y-m-d H:i:s');
                    $groupUser['enter_type'] = Status::GROUP_USER_JOIN_TYPE_INVITE; //1-申请进群  2-邀请进群
                    $groupUser['invite_user_id'] = $inviteUser['id'];
                    $groupUser['invite_user_phone'] = $inviteUser['login_name'];
                    $groupUser['invite_user_tx_code'] = $inviteUser['tx_code'];
                    $groupUser['invite_user_code'] = $inviteUser['user_code'];


                    $groupUserRes = GroupUser::insertData($groupUser);
                    if ($groupUserRes === false) {
                        throw new Exception('群创建失败！');
                    }


                    $singleMember['Member_Account'] = (string) $user['tx_code'];
                    $singleMember['NameCard'] = $user['nick_name'];
                    $singleMember['enter_type'] = (string) Status::GROUP_USER_JOIN_TYPE_INVITE;
                    $singleMember['invite_code'] = (string) $inviteUser['tx_code'];
                    array_push($memberList, $singleMember);


                    // 添加群成员
                    //                    $addImGroupRes = $imModel -> addGroupMember($groupInfo['tx_code'], $memberList);
                    $addImGroupRes = $imModel->addImGroupUser($groupInfo['tx_code'], $memberList);
                    if (!$addImGroupRes) {
                        throw new Exception('操作失败！');
                    }


                    // 修改群头像
                    (new Group())->_updateGroupPic($groupInfo['id']);

                    // 发送im消息
                    $publicGroupMessage['message_type'] = Status::MESSAGE_TYPE_GROUP_PUBLIC;
                    $publicGroupMessage['type'] = Status::MESSAGE_TYPE_GROUP_USER_INVITE_USER;
                    $publicGroupMessage['oneTxCode'] = $inviteGroupUser['tx_code'];
                    $publicGroupMessage['oneNIckName'] = $inviteGroupUser['nick_name'];
                    $publicGroupMessage['twoTxCode'] = $user['tx_code'];
                    $publicGroupMessage['towNIckName'] = $user['nick_name'];
                    $publicGroupMessage['content'] = $inviteUser['nick_name'] . "邀请" . $user['nick_name'] . "加入群聊！";
                    $imModel->sendGroupMessage($groupInfo['tx_code'], $publicGroupMessage);

                    // 未读数量
                    FriendApply::notReadApplyNum($user['id']);
                    FriendApply::notReadApplyNum($user['id'], $groupInfo['id']);
                }
            }

            $trans->commit();
            return Functions::formatRestAPI(0, '处理成功');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 处理群申请 - 群主或者群管理 邀请处理
     * @return array
     */
    public function check()
    {
        $trans = static::getDb()->beginTransaction();

        try {
            $redis = Yii::$app->redis;
            $user = (new User())->checkUser();
            CacheKeys::checkFrequency($user['id'], 1);

            $id = Yii::$app->request->post('id', 0);
            $state = Yii::$app->request->post('state', 0);

            if (!$id) {
                throw new Exception('未知申请信息！');
            }

            if (!$state) {
                throw new Exception('审核状态有误！');
            }

            if (!in_array($state, [Status::COMMON_CHECKING_SUCCESS, Status::COMMON_CHECKING_DEFEAT])) {
                throw new Exception('审核状态有误！');
            }

            $info = static::getOneByWhere(['id' => $id]);
            if (empty($info)) {
                throw new Exception('申请信息不存在！');
            }

            if ($info['status'] != Status::COMMON_CHECKING_WAITING) {
                throw new Exception('申请信息已处理！');
            }

            if ($info['be_invited_status'] != Status::COMMON_CHECKING_SUCCESS) {
                throw new Exception('被邀请人还未同意！');
            }


            $applyUser = User::getObjectByWhere(['id' => $info['user_id']])->with()->asArray()->one();
            if (empty($applyUser)) {
                throw new Exception('该用户不存在！');
            }

            UserUnusualLog::checkUserUnusual($info['user_id'],Status::USER_UNUSUAL_TYPE_GROUP_CHAT);
            
            $groupInfo = Group::getObjectOneByWhere(['id' => $info['group_id']])->with([])->asArray()->one();
            if (empty($groupInfo)) {
                throw new Exception('群信息不存在！');
            }

            if ($groupInfo['status'] == Status::COMMON_RADIO_NO) {
                throw new Exception('群已被封禁！');
            }

            // 是否加群
            $isGroupUser = GroupUser::getCountByWhere([
                'user_id' => $applyUser['id'],
                'group_id' => $info['group_id'],
            ]);
            if ($isGroupUser) {
                throw new Exception('该用户已在群中！');
            }

            // 是否是管理员或者群主
            $handleGroupUser = GroupUser::getObjectByWhere([
                'user_id' => $user['id'],
                'group_id' => $info['group_id'],
            ])->with([
                'user' => function ($q) {
                    $q->select(['id', 'login_name', 'user_face', 'nick_name', 'tx_code', 'user_code']);
                }

            ])->asArray()->one();
            if (empty($handleGroupUser)) {
                throw new Exception('非法请求（你不是该群成员）！');
            }

            if ($handleGroupUser['user_type'] != Status::GROUP_USER_TYPE_HOME && $handleGroupUser['user_type'] != Status::GROUP_USER_TYPE_MANAGE) {
                throw new Exception('您不是群主或管理员，无法操作！');
            }

            $updateData['handle_user_id'] = $handleGroupUser['id'];
            $updateData['handle_user_tx_code'] = $handleGroupUser['tx_code'];
            $updateData['handle_user_code'] = $handleGroupUser['user_code'];
            $updateData['handle_time'] = date('Y-m-d H:i:s');
            $updateData['status'] = $state;
            $res = static::updateData($updateData, ['id' => $id]);
            if ($res === false) {
                throw new Exception('操作失败！');
            }

            $inviteGroupUser = GroupUser::getObjectByWhere([
                'user_id' => $info['invite_user_id'],
                'group_id' => $info['group_id'],
            ])->with([
                'inviteUser' => function ($q) {
                    $q->select(['id', 'login_name', 'user_face', 'nick_name', 'tx_code', 'user_code']);
                },

            ])->asArray()->one();

            $memberList = [];
            $imModel = new Im();

            if ($state == Status::COMMON_CHECKING_SUCCESS) {
                // 判断是否是群主或者管理邀请 直接进群
                $groupImInfo = $imModel->getGroupInfo($groupInfo['tx_code']);
                if ($groupImInfo['MemberNum'] + 1 >  $groupImInfo['MaxMemberNum']) {
                    throw new Exception('该群人员已达上限！');
                }

                $inviteUser = ArrayHelper::getValue($inviteGroupUser, 'inviteUser', []);
                $groupUser = [];
                $groupUser['group_id'] = $groupInfo['id'];
                $groupUser['group_tx_code'] = $groupInfo['tx_code'];
                $groupUser['group_code'] = $groupInfo['code'];
                $groupUser['group_name'] = $groupInfo['name'];
                //                $groupUser['group_image'] = $groupInfo['image'];
                $groupUser['user_id'] = $applyUser['id'];
                $groupUser['user_tx_code'] = $applyUser['tx_code'];
                $groupUser['user_face'] = $applyUser['user_face'];
                $groupUser['user_nick_name'] = $applyUser['nick_name'];
                //                $groupUser['business_card'] = $user['nick_name'];
                $groupUser['business_card'] = '';
                $groupUser['user_code'] = $applyUser['user_code'];
                $groupUser['user_phone'] = $applyUser['login_name'];
                $groupUser['user_type'] = Status::GROUP_USER_TYPE_NORMAL;
                $groupUser['is_shut_up'] = Status::COMMON_RADIO_NO;   //禁言
                $groupUser['is_not_disturbing'] = Status::COMMON_RADIO_NO;   //是否消息免打扰
                $groupUser['is_receive_red_packet'] = Status::COMMON_RADIO_YES;  // 是否可以抢红包
                $groupUser['create_time'] = date('Y-m-d H:i:s');
                $groupUser['enter_type'] = Status::GROUP_USER_JOIN_TYPE_INVITE; //1-申请进群  2-邀请进群
                $groupUser['invite_user_id'] = $inviteUser['id'];
                $groupUser['invite_user_phone'] = $inviteUser['login_name'];
                $groupUser['invite_user_tx_code'] = $inviteUser['tx_code'];
                $groupUser['invite_user_code'] = $inviteUser['user_code'];

                $singleMember['enter_type'] = (string) Status::GROUP_USER_JOIN_TYPE_INVITE;
                $singleMember['invite_code'] = (string) $inviteUser['tx_code'];
                // 不是邀请  是自己申请
                if ($info['enter_type'] != Status::GROUP_USER_JOIN_TYPE_INVITE) {
                    $groupUser['enter_type'] = $info['enter_type'];
                    $groupUser['invite_user_id'] = $user['id'];
                    $groupUser['invite_user_phone'] = $user['login_name'];
                    $groupUser['invite_user_tx_code'] = $user['tx_code'];
                    $groupUser['invite_user_code'] = $user['user_code'];
                    $singleMember['enter_type'] = (string) $info['enter_type'];
                    $singleMember['invite_code'] = "0";
                }

                $groupUserRes = GroupUser::insertData($groupUser);
                if ($groupUserRes === false) {
                    throw new Exception('群创建失败！');
                }


                $singleMember['Member_Account'] = (string) $applyUser['tx_code'];
                $singleMember['NameCard'] = $applyUser['nick_name'];
                array_push($memberList, $singleMember);

                // 添加群成员
                //                $addImGroupRes = $imModel -> addGroupMember($groupInfo['tx_code'], $memberList);
                $addImGroupRes = $imModel->addImGroupUser($groupInfo['tx_code'], $memberList);
                if (!$addImGroupRes) {
                    throw new Exception('操作失败！');
                }

                // 更换群头像 - 群没有上传头像的时候才会更新群头像
                (new Group())->_updateGroupPic($groupInfo['id']);

                // 发送im消息
                $publicGroupMessage['message_type'] = Status::MESSAGE_TYPE_GROUP_PUBLIC;
                $publicGroupMessage['type'] = Status::MESSAGE_TYPE_GROUP_USER_INVITE_USER;
                $publicGroupMessage['oneTxCode'] = $inviteGroupUser['tx_code'];
                $publicGroupMessage['oneNIckName'] = $inviteGroupUser['nick_name'];
                $publicGroupMessage['twoTxCode'] = $applyUser['tx_code'];
                $publicGroupMessage['towNIckName'] = $applyUser['nick_name'];
                if ($info['enter_type'] == Status::GROUP_USER_JOIN_TYPE_INVITE) {
                    // 有邀请人
                    $publicGroupMessage['content'] = $inviteUser['nick_name'] . "邀请" . $applyUser['nick_name'] . "加入群聊！";
                } else {
                    // 自己申请
                    $publicGroupMessage['type'] = Status::MESSAGE_TYPE_GROUP_USER_APPLY;
                    $publicGroupMessage['oneTxCode'] = $applyUser['tx_code'];
                    $publicGroupMessage['oneNIckName'] = $applyUser['nick_name'];
                    $publicGroupMessage['content'] = $applyUser['nick_name'] . "加入群聊！";
                }


                $imModel->sendGroupMessage($groupInfo['tx_code'], $publicGroupMessage);

                // 未读数量
                FriendApply::notReadApplyNum($user['id'], $groupInfo['id']);
            }

            $trans->commit();
            return Functions::formatRestAPI(0, '处理成功');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }
}
